package com.server;


import com.serializetool.handler.RpcDecoder;
import com.serializetool.handler.RpcEncoder;
import com.service.ServiceBuilder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ServerBuilder {
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServiceBuilder serviceBuilder;
    public void init(int port){
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootStrap = new ServerBootstrap();
            serverBootStrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new RpcEncoder());
                            ch.pipeline().addLast(new RpcDecoder());
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_KEEPALIVE, true);;
            ChannelFuture channelFuture = serverBootStrap.bind(port).sync();
            System.out.println("服务器绑定端口成功");
            channelFuture.channel().closeFuture().sync();
            serviceBuilder = new ServiceBuilder();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close(){
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        serviceBuilder.close();
    }
}
